package cn.ztuo.bitrade.controller;

import cn.ztuo.bitrade.constant.BooleanEnum;
import cn.ztuo.bitrade.constant.MemberLevelEnum;
import cn.ztuo.bitrade.entity.*;
import cn.ztuo.bitrade.entity.transform.AuthMember;
import cn.ztuo.bitrade.service.*;
import cn.ztuo.bitrade.util.*;
import cn.ztuo.bitrade.vo.AccessRecordVO;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

import static cn.ztuo.bitrade.constant.SysConstant.SESSION_MEMBER;

/**
 * @author: Xiazt
 * @date: 2020-05-07 10:08
 */
//@RestController
//@RequestMapping("accessRecord")
public class AccessRecordController extends BaseController {

    @Autowired
    private AccessRecordService accessRecordService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private MemberWalletService memberWalletService;

    @Autowired
    private AccessServiceChargeService accessServiceChargeService;

    @Autowired
    private BorrowMoneyService borrowMoneyService;

    @Autowired
    private LoanMoneyService loanMoneyService;

    /**
     * 借入 / 借出
     *
     * @param authMember
     * @param accessRecord
     * @param jyPassword
     * @return
     */
    @RequestMapping("access")
    public MessageResult access(@SessionAttribute(SESSION_MEMBER) AuthMember authMember,
                                AccessRecord accessRecord,
                                String jyPassword,
                                String pledgeCoinUnit,
                                Long moneyId,
                                HttpServletRequest request) {
        try {
            if (jyPassword == null || jyPassword.equals("")) return error("交易密码不能为空！");
            //验证用户信息
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) return error("您当前账户已禁用，请联系客服！");
            if (member.getMemberLevel() == MemberLevelEnum.GENERAL) error("请先进行实名认证！");

            //验证交易密码
            String mbPassword = member.getJyPassword();
            if (mbPassword == null || mbPassword.equals("")) return MessageResult.error(500, "请先设置交易密码！");
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
                return MessageResult.error(500, "交易密码错误！");


            Coin coin = coinService.findByUnit("USDT");
            BigDecimal residueMoney = null;
            MemberWallet memberWallet = memberWalletService.findByCoinAndMember(coin, member);
            if (accessRecord.getType() == 0) {
                if (authMember.getId() == accessRecord.getLoanMoney().getJoinMember().getId()) return error("不可购买自己发布的借贷！");
                // 计算手续费
                AccessServiceCharge serviceCharge = accessServiceChargeService.findByCoin(coin);
                BigDecimal chargeRate = BigDecimalUtils.div(serviceCharge.getServiceChange(), new BigDecimal(100));
                BigDecimal charge = BigDecimalUtils.mul(accessRecord.getMoney(), chargeRate);
                if (charge.compareTo(BigDecimal.ZERO) <= 0) return error("数据异常！");
                accessRecord.setServiceCharge(charge);
                if (memberWallet.getBalance().compareTo(accessRecord.getServiceCharge()) < 0) return error("手续费不足！");

                // 验证剩余数量
                LoanMoney loanMoney = loanMoneyService.findById(moneyId);
                residueMoney = BigDecimalUtils.sub(loanMoney.getLoanAmount(), loanMoney.getHasLoanAmount());

                // 计算质押金额
                MessageResult coinRate = getCoinRate(pledgeCoinUnit);
                // 获取汇率
                String closePrice = coinRate.getMessage();
                // 质押金 = 借款金额 / 70% / 汇率
                BigDecimal pledgeMoney = BigDecimalUtils.div(BigDecimalUtils.div(accessRecord.getMoney(), new BigDecimal(0.7)), new BigDecimal(closePrice));
                if (pledgeMoney.compareTo(BigDecimal.ZERO) <= 0) return error("数据异常！");
                accessRecord.setPledgeMoney(pledgeMoney);
                Coin pledgeCoin = coinService.findByUnit(pledgeCoinUnit);
                MemberWallet pledgeMemberWallet = memberWalletService.findByCoinAndMember(pledgeCoin, member);
                if (pledgeMemberWallet.getBalance().compareTo(accessRecord.getPledgeMoney()) < 0)
                    return error("质押金额不足！");

                // 计算利息
                BigDecimal mul = BigDecimalUtils.mul(accessRecord.getMoney(), BigDecimalUtils.div(loanMoney.getDayRate(), new BigDecimal(100)));
                BigDecimal interest = BigDecimalUtils.mul(mul, loanMoney.getPeriod());
                if (interest.compareTo(BigDecimal.ZERO) <= 0) return error("数据异常！");
                accessRecord.setInterest(interest);
            } else {
                if (authMember.getId() == accessRecord.getBorrowMoney().getJoinMember().getId()) return error("不可购买自己发布的借贷！");

                if (memberWallet.getBalance().compareTo(accessRecord.getMoney()) < 0) return error("余额不足！");
                // 验证剩余数量
                BorrowMoney borrowMoney = borrowMoneyService.findById(moneyId);
                residueMoney = BigDecimalUtils.sub(borrowMoney.getBorrowAmount(), borrowMoney.getHasBorrowAmount());
            }
            // 验证交易金额
            if (accessRecord.getMoney().compareTo(BigDecimal.ZERO) <= 0) {
                FileUtil.writeErrorLog(request.getRemoteAddr(), accessRecord.getMoney(), member.getId());
                return error("数据异常！");
            }
            if (residueMoney.compareTo(accessRecord.getMoney()) < 0) {
                return error("超出总借贷金额！");
            }
            // 业务
            accessRecordService.access(authMember.getId(), accessRecord, pledgeCoinUnit, moneyId);
            return success();

        } catch (Exception e) {
            e.printStackTrace();
            return error("网络繁忙，请稍后再试！！");
        }
    }

    /**
     * 获取我的当前 借入 / 借出单
     *
     * @param authMember
     * @param accessRecordVO
     * @return
     */
    @RequestMapping("getMyAccessRecord")
    public MessageResult getMyAccessRecord(@SessionAttribute(SESSION_MEMBER) AuthMember authMember, AccessRecordVO accessRecordVO) {
        accessRecordVO.setMemberId(authMember.getId());
        return success(accessRecordService.getMyAccessRecord(accessRecordVO));
    }

    /**
     * 还款
     *
     * @param authMember
     * @param accessId
     * @param jyPassword
     * @return
     */
    @RequestMapping("repayment")
    public MessageResult repayment(@SessionAttribute(SESSION_MEMBER) AuthMember authMember, Long accessId, String jyPassword) {
        try {
            if (jyPassword == null || jyPassword.equals("")) return error("交易密码不能为空！");
            //验证用户信息
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) return error("您当前账户已禁用，请联系客服！");
            if (member.getMemberLevel() == MemberLevelEnum.GENERAL) error("请先进行实名认证！");

            //验证交易密码
            String mbPassword = member.getJyPassword();
            if (mbPassword == null || mbPassword.equals("")) return MessageResult.error(500, "请先设置交易密码！");
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
                return MessageResult.error(500, "交易密码错误！");

            // 验证余额
            Coin coin = coinService.findByUnit("USDT");
            MemberWallet memberWallet = memberWalletService.findByCoinAndMember(coin, member);
            AccessRecord accessRecord = accessRecordService.findById(accessId);
            BigDecimal interest = BigDecimal.ZERO;
            if (accessRecord.getType() == 0) {
                interest = accessRecord.getInterest();
            } else {
                interest = accessRecord.getBorrowMoney().getInterestDue();
            }
            BigDecimal money = BigDecimalUtils.add(accessRecord.getMoney(), interest);
            if (memberWallet.getBalance().compareTo(money) < 0) return error("余额不足！");

            // 业务
            accessRecordService.repayment(accessId);
            return success();

        } catch (Exception e) {
            e.printStackTrace();
            return error("服务器异常！");
        }
    }

    /**
     * 获取币种手续费
     *
     * @param unit
     * @return
     */
    @RequestMapping("getCoinServiceChange")
    public MessageResult getCoinServiceChange(String unit) {
        Coin coin = coinService.findByUnit(unit);
        return success(accessServiceChargeService.findByCoin(coin));
    }

    /**
     * 获取币种对USDT汇率
     *
     * @param unit
     * @return
     */
    @RequestMapping("getCoinRate")
    public MessageResult getCoinRate(String unit) {
        try {
            // 获取当前汇率
            String url = "https://api.huobi.pro/market/detail/merged?symbol=" + unit.toLowerCase() + "usdt";
            String resultString = HttpsUtil.doGet(url);
            JSONObject result = JSONObject.parseObject(resultString);
            JSONObject tick = result.getJSONObject("tick");
            BigDecimal closePrice = tick.getBigDecimal("close");
            return success(closePrice.toString());
//            return success("9304.7");
        } catch (Exception e) {
            e.printStackTrace();
            return error("网络繁忙，请稍后再试！！");
        }
    }

    /**
     * 补仓
     *
     * @param authMember
     * @param accessRecordId
     * @param money
     * @return
     */
    @RequestMapping("variationCall")
    public MessageResult variationCall(@SessionAttribute(SESSION_MEMBER) AuthMember authMember, Long accessRecordId, BigDecimal money, String jyPassword, HttpServletRequest request) {
        try {

            if (money.compareTo(BigDecimal.ZERO) <= 0) {
                FileUtil.writeErrorLog(request.getRemoteAddr(),money,authMember.getId());
                return error("数据异常！");
            }

            if (jyPassword == null || jyPassword.equals("")) return error("交易密码不能为空！");
            //验证用户信息
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) return error("您当前账户已禁用，请联系客服！");
            if (member.getMemberLevel() == MemberLevelEnum.GENERAL) error("请先进行实名认证！");

            //验证交易密码
            String mbPassword = member.getJyPassword();
            if (mbPassword == null || mbPassword.equals("")) return MessageResult.error(500, "请先设置交易密码！");
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
                return MessageResult.error(500, "交易密码错误！");

            // 验证余额
            AccessRecord accessRecord = accessRecordService.findById(accessRecordId);
            if (accessRecord.getType() == 0) {
                Coin pledgeCoin = accessRecord.getJoinPledgeCoin();
                MemberWallet pledgeMemberWallet = memberWalletService.findByCoinAndMemberId(pledgeCoin, authMember.getId());
                if (pledgeMemberWallet.getBalance().compareTo(money) < 0) return error("余额不足");
            }

            accessRecordService.variationCall(authMember.getId(), accessRecordId, money);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error("服务器异常!");
        }
    }

}
